import React, { useState, useEffect } from 'react';
import {
  Button,
  Input,
  Label,
  Text,
  Spinner,
  Table,
  TableHeader,
  TableRow,
  TableHead,
  TableBody,
  TableCell,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
  Checkbox
} from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { Counselor, getCounselors, addCounselor, updateCounselor, deleteCounselor } from '../mock/counselorData';

// 性别选项
const genderOptions = ['男', '女', '其他'];

// 学院选项（与成绩管理系统中的educationStage保持一致）
const departmentOptions = ['人工智能学院', '新媒体学院', '计算机学院', '电子工程学院', '机械工程学院', '经济管理学院', '外国语学院', '文学院', '医学院', '艺术学院'];

// 职位选项
const positionOptions = ['辅导员', '副辅导员', '班主任', '年级主任', '学院辅导员办公室主任'];

export default function CounselorManagementPage() {
  const { session } = useSession();
  const [counselors, setCounselors] = useState<Counselor[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentCounselor, setCurrentCounselor] = useState<Counselor | null>(null);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDeleteOpen, setIsDeleteOpen] = useState(false);
  const [form, setForm] = useState({
    name: '',
    gender: '男',
    phone: '',
    department: '人工智能学院', // 默认值与成绩管理系统保持一致
    position: '辅导员',
    hireDate: '',
    status: true,
    classes: [] as string[],
  });
  const [alert, setAlert] = useState('');
  const [showAlert, setShowAlert] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [genderFilter, setGenderFilter] = useState<string>('all');
  const [departmentFilter, setDepartmentFilter] = useState<string>('all');
  const [positionFilter, setPositionFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>('all');

  // 分页和批量删除相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [selectedCounselors, setSelectedCounselors] = useState<number[]>([]);
  const [selectAll, setSelectAll] = useState(false);

  // 权限检查
  const canEdit = session?.userRole === 'admin' || session?.userRole === 'user';
  const canDelete = session?.userRole === 'admin';
  const canAdd = session?.userRole === 'admin';

  // 加载辅导员数据
  useEffect(() => {
    loadCounselors();
  }, []);

  const loadCounselors = async () => {
    setLoading(true);
    try {
      // 清除localStorage中的旧数据，确保获取包含新字段的完整数据
      localStorage.removeItem('counselors');
      
      // 调用API获取最新数据
      const counselorsData = await getCounselors();
      setCounselors(counselorsData);
      // 保存到localStorage
      localStorage.setItem('counselors', JSON.stringify(counselorsData));
    } catch (error) {
      console.error('加载辅导员列表失败:', error);
      setAlert('加载辅导员列表失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value, type, checked } = e.target;
    setForm(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  // 重置表单
  const resetForm = () => {
    setForm({
      name: '',
      gender: '男',
      phone: '',
      department: '人工智能学院',
      position: '辅导员',
      hireDate: '',
      status: true,
      classes: [] as string[],
    });
  };

  // 添加辅导员
  const handleAdd = async () => {
    try {
      // 表单验证
      if (!form.name || !form.phone || !form.hireDate) {
        setAlert('请填写必填字段');
        setShowAlert(true);
        return;
      }

      // 调用mock API添加辅导员
      const { name, gender, phone, department, position, hireDate, status, classes } = form;
      const newCounselor = await addCounselor({
        name,
        gender,
        phone,
        email: '', // 保留此字段以兼容后端
        department,
        position,
        hireDate,
        status,
        classes,
        studentCount: 0 // 保留此字段以兼容后端
      });
      
      // 更新本地状态
      const updatedCounselors = [...counselors, newCounselor];
      setCounselors(updatedCounselors);
      
      // 保存到localStorage
      localStorage.setItem('counselors', JSON.stringify(updatedCounselors));
      
      setIsAddOpen(false);
      setAlert('添加辅导员成功');
      setShowAlert(true);
    } catch (error) {
      console.error('添加辅导员失败:', error);
      setAlert('添加辅导员失败');
      setShowAlert(true);
    }
  };

  // 编辑辅导员
  const handleEdit = async () => {
    if (!currentCounselor) return;
    try {
      // 表单验证
      if (!form.name || !form.phone || !form.hireDate) {
        setAlert('请填写必填字段');
        setShowAlert(true);
        return;
      }

      // 调用mock API编辑辅导员
      const { name, gender, phone, department, position, hireDate, status, classes } = form;
      const updatedCounselor = await updateCounselor(currentCounselor.id, {
        name,
        gender,
        phone,
        email: '', // 保留此字段以兼容后端
        department,
        position,
        hireDate,
        status,
        classes,
        studentCount: 0 // 保留此字段以兼容后端
      });
      
      // 更新本地状态
      const updatedCounselors = counselors.map(counselor => 
        counselor.id === updatedCounselor.id ? updatedCounselor : counselor
      );
      setCounselors(updatedCounselors);
      
      // 保存到localStorage
      localStorage.setItem('counselors', JSON.stringify(updatedCounselors));
      
      setIsEditOpen(false);
      setAlert('编辑辅导员成功');
      setShowAlert(true);
    } catch (error) {
      console.error('编辑辅导员失败:', error);
      setAlert('编辑辅导员失败');
      setShowAlert(true);
    }
  };

  // 删除辅导员
  const handleDelete = async () => {
    if (!currentCounselor) return;
    try {
      // 调用mock API删除辅导员
      await deleteCounselor(currentCounselor.id);
      
      // 更新本地状态
      const updatedCounselors = counselors.filter(counselor => counselor.id !== currentCounselor.id);
      setCounselors(updatedCounselors);
      
      // 保存到localStorage
      localStorage.setItem('counselors', JSON.stringify(updatedCounselors));
      
      setIsDeleteOpen(false);
      setAlert('删除辅导员成功');
      setShowAlert(true);
    } catch (error) {
      console.error('删除辅导员失败:', error);
      setAlert('删除辅导员失败');
      setShowAlert(true);
    }
  };

  // 处理批量删除
  const handleBatchDelete = async () => {
    if (selectedCounselors.length === 0) {
      setAlert('请选择要删除的辅导员');
      setShowAlert(true);
      return;
    }

    try {
      // 模拟批量删除API调用
      for (const counselorId of selectedCounselors) {
        await deleteCounselor(counselorId);
      }
      
      const updatedCounselors = counselors.filter(counselor => !selectedCounselors.includes(counselor.id));
      setCounselors(updatedCounselors);
      setSelectedCounselors([]);
      setSelectAll(false);
      
      // 保存到localStorage
      localStorage.setItem('counselors', JSON.stringify(updatedCounselors));
      
      setAlert(`成功删除 ${selectedCounselors.length} 个辅导员`);
      setShowAlert(true);
    } catch (error) {
      console.error('批量删除辅导员失败:', error);
      setAlert('批量删除辅导员失败');
      setShowAlert(true);
    }
  };

  // 辅导员选择处理
  const handleSelectCounselor = (counselorId: number, checked: boolean) => {
    if (checked) {
      setSelectedCounselors([...selectedCounselors, counselorId]);
    } else {
      setSelectedCounselors(selectedCounselors.filter(id => id !== counselorId));
      setSelectAll(false);
    }
  };

  // 全选处理
  const handleSelectAll = (checked: boolean) => {
    setSelectAll(checked);
    if (checked) {
      setSelectedCounselors(filteredCounselors.map(counselor => counselor.id));
    } else {
      setSelectedCounselors([]);
    }
  };

  // 过滤辅导员列表
  const filteredCounselors = counselors.filter(counselor =>
    // 搜索条件
    (counselor.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
     counselor.phone.includes(searchTerm) ||
     counselor.department.toLowerCase().includes(searchTerm.toLowerCase())) &&
    // 性别筛选
    (genderFilter === 'all' || counselor.gender === genderFilter) &&
    // 学院筛选
    (departmentFilter === 'all' || counselor.department === departmentFilter) &&
    // 职位筛选
    (positionFilter === 'all' || counselor.position === positionFilter) &&
    // 状态筛选
    (statusFilter === 'all' || counselor.status === (statusFilter === 'active'))
  );

  // 分页逻辑
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = filteredCounselors.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.max(1, Math.ceil(filteredCounselors.length / itemsPerPage));

  // 分页处理函数
  const goToPage = (page: number) => {
    setCurrentPage(Math.max(1, Math.min(page, totalPages)));
  };

  const nextPage = () => {
    if (currentPage < totalPages) {
      setCurrentPage(currentPage + 1);
    }
  };

  const prevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setItemsPerPage(parseInt(e.target.value));
    setCurrentPage(1);
  };

  // 打开添加对话框
  const handleAddOpen = () => {
    resetForm();
    setIsAddOpen(true);
  };

  // 打开编辑对话框
  const handleEditOpen = (counselor: Counselor) => {
    setCurrentCounselor(counselor);
    setForm({
      name: counselor.name,
      gender: counselor.gender,
      phone: counselor.phone,
      department: counselor.department,
      position: counselor.position,
      hireDate: counselor.hireDate,
      status: counselor.status,
      classes: counselor.classes || [],
    });
    setIsEditOpen(true);
  };

  // 打开删除对话框
  const handleDeleteOpen = (counselor: Counselor) => {
    setCurrentCounselor(counselor);
    setIsDeleteOpen(true);
  };

  return (
    <div className="p-6 bg-white">
      {/* 页面标题和操作按钮 */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6 gap-4">
        <Text className="text-2xl font-bold text-gray-900">辅导员管理</Text>
        <div className="flex items-center gap-3">
          {/* 批量删除按钮 */}
          {canDelete && (
            <Button 
              variant="destructive" 
              onClick={handleBatchDelete}
              disabled={selectedCounselors.length === 0}
            >
              批量删除 ({selectedCounselors.length})
            </Button>
          )}
          {canAdd && (
            <Button variant="primary" onClick={handleAddOpen}>
              添加辅导员
            </Button>
          )}
        </div>
      </div>

      {/* 搜索和筛选 */}
      <div className="mb-6">
        <div className="relative max-w-md mb-4">
          <Input
            type="text"
            placeholder="搜索辅导员姓名、电话或所属学院..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <span className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">🔍</span>
        </div>
        
        {/* 筛选控件 */}
        <div className="flex flex-wrap gap-4 mb-4">
          {/* 性别筛选 */}
          <div className="flex items-center gap-2">
            <Label htmlFor="gender-filter">性别:</Label>
            <select
              id="gender-filter"
              value={genderFilter}
              onChange={(e) => { setGenderFilter(e.target.value); setCurrentPage(1); }}
              className="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">全部</option>
              {genderOptions.map(gender => (
                <option key={gender} value={gender}>{gender}</option>
              ))}
            </select>
          </div>
          
          {/* 学院筛选 */}
          <div className="flex items-center gap-2">
            <Label htmlFor="department-filter">所属学院:</Label>
            <select
              id="department-filter"
              value={departmentFilter}
              onChange={(e) => { setDepartmentFilter(e.target.value); setCurrentPage(1); }}
              className="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">全部</option>
              {departmentOptions.map(department => (
                <option key={department} value={department}>{department}</option>
              ))}
            </select>
          </div>
          
          {/* 职位筛选 */}
          <div className="flex items-center gap-2">
            <Label htmlFor="position-filter">职位:</Label>
            <select
              id="position-filter"
              value={positionFilter}
              onChange={(e) => { setPositionFilter(e.target.value); setCurrentPage(1); }}
              className="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">全部</option>
              {positionOptions.map(position => (
                <option key={position} value={position}>{position}</option>
              ))}
            </select>
          </div>
          
          {/* 状态筛选 */}
          <div className="flex items-center gap-2">
            <Label htmlFor="status-filter">状态:</Label>
            <select
              id="status-filter"
              value={statusFilter}
              onChange={(e) => { setStatusFilter(e.target.value); setCurrentPage(1); }}
              className="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="all">全部</option>
              <option value="active">在职</option>
              <option value="inactive">离职</option>
            </select>
          </div>
          
          {/* 重置筛选按钮 */}
          <Button
            variant="ghost"
            onClick={() => {
              setGenderFilter('all');
              setDepartmentFilter('all');
              setPositionFilter('all');
              setStatusFilter('all');
              setSearchTerm('');
              setCurrentPage(1);
            }}
          >
            重置筛选
          </Button>
        </div>
      </div>

      {/* 警告提示 */}
      {showAlert && (
        <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
          <Text className="text-blue-700">{alert}</Text>
          <Button 
           variant="ghost"
            size="sm" 
            onClick={() => setShowAlert(false)}
            className="absolute right-3 top-2 text-blue-500"
          >
            ×
          </Button>
        </div>
      )}

      {/* 辅导员列表表格 */}
      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-16">
                <Checkbox
                  checked={selectAll}
                  onChange={(e) => handleSelectAll(e.target.checked)}
                  disabled={filteredCounselors.length === 0}
                />
              </TableHead>
              <TableHead className="w-16">ID</TableHead>
              <TableHead>姓名</TableHead>
              <TableHead>性别</TableHead>
              <TableHead>电话</TableHead>
              <TableHead>所属学院</TableHead>
              <TableHead>职位</TableHead>
              <TableHead>入职日期</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>所带班级</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={13} className="text-center py-8">
                  <Spinner className="mx-auto" />
                </TableCell>
              </TableRow>
            ) : currentItems.length === 0 ? (
              <TableRow>
                <TableCell colSpan={13} className="text-center py-8">
                    暂无辅导员数据
                  </TableCell>
              </TableRow>
            ) : (
              currentItems.map((counselor) => (
                <TableRow key={counselor.id}>
                  <TableCell>
                    <Checkbox
                      checked={selectedCounselors.includes(counselor.id)}
                      onChange={(e) => handleSelectCounselor(counselor.id, e.target.checked)}
                    />
                  </TableCell>
                    <TableCell>{counselor.id}</TableCell>
                    <TableCell>{counselor.name}</TableCell>
                    <TableCell>{counselor.gender}</TableCell>
                    <TableCell>{counselor.phone}</TableCell>
                    <TableCell>{counselor.department}</TableCell>
                    <TableCell>{counselor.position}</TableCell>
                    <TableCell>{counselor.hireDate}</TableCell>
                    <TableCell>
                      <span className={`px-2 py-1 rounded text-xs ${counselor.status ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
                        {counselor.status ? '在职' : '离职'}
                      </span>
                    </TableCell>
                    <TableCell>
                      {counselor.classes ? counselor.classes.join('、') : '-'}
                    </TableCell>
                  <TableCell>
                    <div className="flex space-x-2">
                      {canEdit && (
                        <Button variant="ghost" onClick={() => handleEditOpen(counselor)}>
                          编辑
                        </Button>
                      )}
                      {canDelete && (
                        <Button variant="ghost" color="red" onClick={() => handleDeleteOpen(counselor)}>
                          删除
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 分页控制 */}
      <div className="mt-6 flex flex-col md:flex-row justify-between items-center gap-4">
        <div className="text-sm text-gray-600">
          显示 {indexOfFirstItem + 1} - {Math.min(indexOfLastItem, filteredCounselors.length)} 共 {filteredCounselors.length} 项
          <select 
            className="ml-2 px-2 py-1 border border-gray-300 rounded-md text-sm"
            value={itemsPerPage}
            onChange={handleItemsPerPageChange}
          >
            <option value="5">5条/页</option>
            <option value="10">10条/页</option>
            <option value="20">20条/页</option>
            <option value="50">50条/页</option>
          </select>
        </div>
        <div className="flex items-center gap-2">
          <Button 
            variant="ghost" 
            size="sm" 
            onClick={prevPage} 
            disabled={currentPage === 1}
          >
            上一页
          </Button>
          {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
            let pageNum;
            if (totalPages <= 5) {
              pageNum = i + 1;
            } else if (currentPage <= 3) {
              pageNum = i + 1;
            } else if (currentPage >= totalPages - 2) {
              pageNum = totalPages - 4 + i;
            } else {
              pageNum = currentPage - 2 + i;
            }
            return (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "primary" : "ghost"}
                size="sm"
                onClick={() => goToPage(pageNum)}
              >
                {pageNum}
              </Button>
            );
          })}
          <Button 
            variant="ghost" 
            size="sm" 
            onClick={nextPage} 
            disabled={currentPage === totalPages}
          >
            下一页
          </Button>
        </div>
      </div>

      {/* 添加辅导员对话框 */}
      <Dialog open={isAddOpen} onOpenChange={setIsAddOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>添加辅导员</DialogTitle>
            <DialogDescription>
              请填写辅导员信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">姓名</Label>
              <Input
                id="name"
                name="name"
                value={form.name}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="gender" className="text-right">性别</Label>
              <select
                id="gender"
                name="gender"
                value={form.gender}
                onChange={handleInputChange}
                className="col-span-3 border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >
                {genderOptions.map(gender => (
                  <option key={gender} value={gender}>{gender}</option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="phone" className="text-right">电话</Label>
              <Input
                id="phone"
                name="phone"
                value={form.phone}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="department" className="text-right">所属学院</Label>
              <select
                id="department"
                name="department"
                value={form.department}
                onChange={handleInputChange}
                className="col-span-3 border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >
                {departmentOptions.map(department => (
                  <option key={department} value={department}>{department}</option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="position" className="text-right">职位</Label>
              <Input
                id="position"
                name="position"
                value={form.position}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="hireDate" className="text-right">入职日期</Label>
              <Input
                id="hireDate"
                name="hireDate"
                type="date"
                value={form.hireDate}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">在职状态</Label>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="status"
                  name="status"
                  checked={form.status}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-blue-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500"
                />
                <Label htmlFor="status" className="ml-2">在职</Label>
              </div>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="classes" className="text-right">所带班级</Label>
              <Input
                id="classes"
                name="classes"
                value={form.classes ? form.classes.join('、') : ''}
                onChange={(e) => handleInputChange({ target: { name: 'classes', value: e.target.value.split('、') } })}
                placeholder="多个班级用顿号分隔"
                className="col-span-3"
              />
            </div>

          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleAdd}>添加</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 编辑辅导员对话框 */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>编辑辅导员</DialogTitle>
            <DialogDescription>
              请修改辅导员信息
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-name" className="text-right">姓名</Label>
              <Input
                id="edit-name"
                name="name"
                value={form.name}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-gender" className="text-right">性别</Label>
              <select
                id="edit-gender"
                name="gender"
                value={form.gender}
                onChange={handleInputChange}
                className="col-span-3 border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >
                {genderOptions.map(gender => (
                  <option key={gender} value={gender}>{gender}</option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-phone" className="text-right">电话</Label>
              <Input
                id="edit-phone"
                name="phone"
                value={form.phone}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-department" className="text-right">所属学院</Label>
              <select
                id="edit-department"
                name="department"
                value={form.department}
                onChange={handleInputChange}
                className="col-span-3 border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                required
              >
                {departmentOptions.map(department => (
                  <option key={department} value={department}>{department}</option>
                ))}
              </select>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-position" className="text-right">职位</Label>
              <Input
                id="edit-position"
                name="position"
                value={form.position}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-hireDate" className="text-right">入职日期</Label>
              <Input
                id="edit-hireDate"
                name="hireDate"
                type="date"
                value={form.hireDate}
                onChange={handleInputChange}
                className="col-span-3"
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">在职状态</Label>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="edit-status"
                  name="status"
                  checked={form.status}
                  onChange={handleInputChange}
                  className="w-4 h-4 text-blue-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500"
                />
                <Label htmlFor="edit-status" className="ml-2">在职</Label>
              </div>
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-classes" className="text-right">所带班级</Label>
              <Input
                id="edit-classes"
                name="classes"
                value={form.classes ? form.classes.join('、') : ''}
                onChange={(e) => handleInputChange({ target: { name: 'classes', value: e.target.value.split('、') } })}
                placeholder="多个班级用顿号分隔"
                className="col-span-3"
              />
            </div>

          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button onClick={handleEdit}>保存</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除辅导员对话框 */}
      <Dialog open={isDeleteOpen} onOpenChange={setIsDeleteOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除该辅导员吗？此操作不可撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline">取消</Button>
            </DialogClose>
            <Button variant="destructive" onClick={handleDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}